import React from 'react';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import type { ParkItem } from '@/services/API.d';
import { columnsParkItem } from '@/services/Column.d';
import ProTable from '@ant-design/pro-table';
import { queryParkList, statePark } from '@/services/park';
import { Button, message } from 'antd';

class Park extends React.Component<any, any> {
  private actionRef = React.createRef<any>();
  public state = {
    selectedRowsState: [],
  };

  setSelectedRows = (selectedRowsState: ParkItem[]) => {
    this.setState({
      selectedRowsState,
    });
  };

  /**
   *  状态更新节点
   * @param selectedRows
   * @param state
   */
  handleState = async (selectedRows: ParkItem[], state: number) => {
    const hide = message.loading('正在操作');
    if (!selectedRows) return true;
    try {
      await statePark(
        selectedRows.map((row) => row.parkId),
        state,
      );
      hide();
      message.success('操作成功');
      return true;
    } catch (error) {
      hide();
      message.error('操作失败，请重试');
      return false;
    }
  };

  render() {
    const { selectedRowsState } = this.state;
    const { actionRef } = this;
    return (
      <PageContainer>
        <ProTable<ParkItem>
          headerTitle="停车记录列表"
          actionRef={actionRef}
          rowKey={(record) => record.parkId}
          search={{
            labelWidth: 120,
          }}
          pagination={{
            showQuickJumper: true,
          }}
          dateFormatter="string"
          request={ async (params) => {
            let res: any = {};
            await queryParkList(params).then(v => {
              res = v;
              res.total = v.msg
            })
            return res;
          }}
          columns={columnsParkItem}
          rowSelection={{
            onChange: (_, selectedRows) => this.setSelectedRows(selectedRows),
          }}
        />
        {selectedRowsState?.length > 0 && (
          <FooterToolbar
            extra={
              <div>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
              </div>
            }
          >
            <Button
              onClick={async () => {
                await this.handleState(selectedRowsState, 1);
                this.setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              批量未付款
            </Button>
            <Button
              type="primary"
              onClick={async () => {
                await this.handleState(selectedRowsState, 2);
                this.setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              批量付款
            </Button>
          </FooterToolbar>
        )}
      </PageContainer>
    );
  }
}

export default Park;
